package com.t18;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuyiwei on 2018/9/2.
 */
public class GetChannel {
    private static final int BSIZE = 1024;

    public static void main(String[] args)  throws Exception{
        FileChannel fc = new FileOutputStream("/Users/xuyiwei/Documents/javaBase/jdk/src/com/t18/TextFile2.txt").getChannel();
//        fc.write(ByteBuffer.wrap("Some 咋111text".getBytes()));
        //这个缓冲区的数据会存放在byte数组中，bytes数组或buff缓冲区任何一方中数据的改动都会影响另一方。
        //其实ByteBuffer底层本来就有一个bytes数组负责来保存buffer缓冲区中的数据，通过allocate方法系统会帮你构造一个byte数组
        fc.write(ByteBuffer.wrap("Some 咋111text".getBytes()));
        fc.close();
        fc = new RandomAccessFile("/Users/xuyiwei/Documents/javaBase/jdk/src/com/t18/TextFile2.txt","rw").getChannel();
//        fc.position(0);
        fc.write(ByteBuffer.wrap("Some1 more".getBytes()));
        fc.close();
        fc = new FileInputStream("/Users/xuyiwei/Documents/javaBase/jdk/src/com/t18/TextFile2.txt").getChannel();
        //从堆空间中分配一个容量大小为capacity的byte数组作为缓冲区的byte数据存储器
        ByteBuffer buff = ByteBuffer.allocate(BSIZE);
        fc.read(buff);
        buff.flip();
        List<Byte> byteList = new ArrayList<>();
        while (buff.hasRemaining()){
            byteList.add(buff.get());
        }
        byte[] bytes = new byte[byteList.size()];
        for(int i=0;i<byteList.size();i++){
            bytes[i] = byteList.get(i);
        }
        System.out.println(new String( bytes,"UTF-8"));
        /**
         * Some text
         Process finished with exit code 0
         */
    }
}
